$(document).ready(function() {
    var VAL ={
        NORMAL     : "0000000"  ,
        EVT_USER   : $("#userId").text(),
        T_XPTOOLOPE : "XPTOOLOPE" ,
        T_XPLSTEQP  : "XPLSTEQP"  ,
        T_XPTOOLCHK : "XPTOOLCHK"
    };

    /**
     * All controls's jquery object/text
     * @type {Object}
     */
    var controlsQuery = {
        W                      : $(window)                  ,
        baySelect              : $("#baySelect")            ,
        toolSelect             : $("#toolSelect")           ,
        toolStatusSelect       : $("#toolStatusSelect")     ,
        beginTimeDatepicker    : $("#beginTimeDatepicker")  ,
        endTimeDatepicker      : $("#endTimeDatepicker")    ,

        mainGrd   :{
            grdId     : $("#toolCheckInfoGrd")   ,
            grdPgText : "#toolCheckInfoPg"       ,
            fatherDiv : $("#toolCheckInfoDiv")
        }
    };

    /**
     * All button's jquery object
     * @type {Object}
     */
    var btnQuery = {
        f1 : $("#f1_btn"),
//        f4 : $("#f4_btn"),
//        f5 : $("#f5_btn"),
        f8 : $("#f8_btn")
    };

    /**
     * All tool functions
     * @type {Object}
     */
    var toolFunc = {
        resetJqgrid :function(){
            controlsQuery.W.unbind("onresize");
            controlsQuery.mainGrd.grdId.setGridWidth(controlsQuery.mainGrd.fatherDiv.width()*0.90);
            controlsQuery.W.bind("onresize", this);
        },
        clearInput : function(){
//            controlsQuery.remarkTxta.val("");
        },

        /**
         * Set data for select
         * @param dataCnt
         * @param arr
         * @param selVal
         * @param queryObj
         */
        setSelectDate : function(dataCnt, arr, selVal, queryObj){
            var i, realCnt;

            queryObj.empty();
            realCnt = parseInt( dataCnt, 10);

            if( realCnt == 1 ){
                if( arr.hasOwnProperty(selVal)){
                    queryObj.append("<option value="+ arr[selVal] +">"+ arr[selVal] +"</option>")
                }
            }else if( realCnt > 1 ){
                for( i = 0; i < realCnt; i++ ){
                    if( arr[i].hasOwnProperty(selVal)){
                        queryObj.append("<option value="+ arr[i][selVal] +">"+ arr[i][selVal] +"</option>");
                    }
                }
            }
            queryObj.select2({
    	    	theme : "bootstrap"
    	    });
        },
        iniBySelect : function(){
            addValueByDataCateFnc("#baySelect","AREA","data_id");
        },
        /**
         * 根据线别和用户，查询出可以操作的机台。By CMJ
         * @returns {Boolean}
         */
        iniToolSelect : function(){
            var inObj, outObj, bay_id;
            bay_id = controlsQuery.baySelect.val();
            if(!bay_id){
                return false;
            }
            inObj = {
                trx_id      : VAL.T_XPLSTEQP,
                action_flg  : 'S'           ,
                bay_id      : bay_id        ,
                user_id     : VAL.EVT_USER  
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                toolFunc.setSelectDate(outObj.tbl_cnt, outObj.oary, "tool_id", controlsQuery.toolSelect);
            }
        },
        iniDateTimePicker : function(){
            var beginTimeDate, endTimeDate;
            controlsQuery.beginTimeDatepicker.datetimepicker({
                language: 'zh-CN'
            });
            controlsQuery.endTimeDatepicker.datetimepicker({
                language: 'zh-CN'
            });

            beginTimeDate = controlsQuery.beginTimeDatepicker.data("datetimepicker");
            beginTimeDate.setLocalDate(new Date());

            endTimeDate = controlsQuery.endTimeDatepicker.data("datetimepicker");
            endTimeDate.setLocalDate(new Date());
        },
        showDataSetDialog : function(ids){
            var rowData,
                itemName,
                grd;
            grd = controlsQuery.mainGrd.grdId;
            rowData = grd.jqGrid("getRowData", ids);
            itemName = rowData['data_dsc'];
            grd._showSimpleInputDialog({
                itemName : itemName,
                callbackFn : function(data) {
                    if($.trim(data.keyInResult)){
                        rowData['data_value'] = $.trim(data.keyInResult);
                        grd.jqGrid('setRowData', ids, rowData);
                    }
                }
            });
        }
    }; 

    /**
     * All button click function
     * @type {Object}
     */
    var btnFunc = {
        //Query
        f1_func : function(){
            var inObj,
                outObj,
                tool_id;
            tool_id = controlsQuery.toolSelect.val();

            if(!tool_id){
                showErrorDialog("","请选择设备代码！");
                return false;
            }

            inObj = {
                trx_id      : VAL.T_XPTOOLCHK ,
                action_flg  : 'F'             ,
                tool_id     : tool_id
            };
            outObj = comTrxSubSendPostJson(inObj);
            if (outObj.rtn_code == VAL.NORMAL) {
                setGridInfo(outObj.oary,"#toolCheckInfoGrd");
            }
        },
        f4_btn : function(){

        },
        f5_btn : function(){

        },
        //Update
        f8_func : function(){
            var rowIds,
                rowCnt,
                rowIndex,
                rowData,
                dataValue,
                grd,
                chkResultObj,
                chkResults,
                inObj,
                outObj;

            chkResultObj = {};
            chkResults = [];
            grd = controlsQuery.mainGrd.grdId;
            rowIds = grd.jqGrid('getDataIDs');
            rowCnt = rowIds.length;
            if( rowCnt >0 ){
                for(rowIndex = 0; rowIndex < rowCnt; rowIndex++) {
                    rowData = grd.jqGrid('getRowData', rowIds[rowIndex]);
                    dataValue = rowData['data_value'];
                    if(!dataValue){
                        showErrorDialog("",rowData['data_dsc']+"未点检！");
                        return false;
                    }

                    chkResultObj = {
                        tool_id     : rowData['tool_id']     ,
                        rep_unit_id : rowData['rep_unit_id'] ,
                        data_pat_id : rowData['data_pat_id'] ,
                        mes_id      : rowData['mes_id']      ,
                        data_id     : rowData['data_id']     ,
                        data_group  : rowData['data_group']  ,
                        data_dsc    : rowData['data_dsc']    ,
                        data_value  : dataValue              ,
                        spec_chk_u  : rowData['spec_chk_u']  ,
                        spec_chk_l  : rowData['spec_chk_l']
                    };
                    chkResults.push(chkResultObj);
                }
                inObj = {
                    trx_id     : VAL.T_XPTOOLCHK,
                    action_flg : "C"            ,
                    evt_usr    : VAL.EVT_USER   ,
                    record_cnt : rowCnt         ,
                    iary       : chkResults
                };
                outObj = comTrxSubSendPostJson(inObj);
                if (outObj.rtn_code == VAL.NORMAL) {
                    showSuccessDialog("点检成功！");
                }
            }

        }
    };

    /**
     * Bind button click action
     */
    var iniButtonAction = function(){
        btnQuery.f1.click(function(){
            btnFunc.f1_func();
        });
//        btnQuery.f4.click(function(){
//            btnFunc.f4_func();
//        });
//        btnQuery.f5.click(function(){
//            btnFunc.f5_func();
//        });
        btnQuery.f8.click(function(){
            btnFunc.f8_func();
        });
    };

    /**
     * grid  initialization
     */
    var iniGridInfo = function(){
        var grdInfoCM = [
            {name: 'tool_id',        index: 'tool_id',        label: '', width: 1 , hidden: true},
            {name: 'rep_unit_id',    index: 'rep_unit_id',    label: '', width: 1 , hidden: true},
            {name: 'data_pat_id',    index: 'data_pat_id',    label: '', width: 1 , hidden: true},
            {name: 'mes_id',         index: 'mes_id',         label: '', width: 1 , hidden: true},
            {name: 'data_group' ,    index: 'data_group',     label: '', width: 1 , hidden: true},

            {name: 'data_dsc',          index: 'data_dsc',         label: MLITEM_GROUP_TAG      , width: 150},
            {name: 'data_value',        index: 'data_value',       label: MLITEM_VALUE_TAG      , width: 60},
            {name: 'spec_chk_u',        index: 'spec_chk_u',       label: U_SPEC_TAG            , width: 80},
            {name: 'spec_chk_l',        index: 'spec_chk_l',       label: L_SPEC_TAG            , width: 80},
            {name: 'data_id'  ,         index: 'data_id',          label: TOOL_CHECK_SEQ_NO_TAG , width: 80}
        ];
        controlsQuery.mainGrd.grdId.jqGrid({
            url:"",
            datatype:"local",
            mtype:"POST",
            height:300,
            width:520,
            shrinkToFit:false,
            scroll:true,
            rownumWidth : true,
            resizable : true,
            rowNum:40,
            loadonce:true,
            fixed:true,
            viewrecords:true,
            multiselect : true,
            pager : controlsQuery.mainGrd.grdPgText,
            colModel: grdInfoCM,
            ondblClickRow: function(ids){
                toolFunc.showDataSetDialog(ids);
            }
        });
    };

    /**
     * Other action bind
     */
    var otherActionBind = function(){
        // Reset size of jqgrid when window resize
        controlsQuery.W.resize(function(){
            toolFunc.resetJqgrid();
        });

        //Stop from auto commit
        $("form").submit(function(){
            return false;
        });

        //Bay select change ==> tool auto refresh
        controlsQuery.baySelect.change(function(){
            toolFunc.iniToolSelect();
        }); 

    };

    /**
     * Ini contorl's data
     */
    var iniContorlData = function(){
        toolFunc.clearInput();

        //Tool info
        toolFunc.iniBySelect();
        toolFunc.iniToolSelect();

        //Time
        toolFunc.iniDateTimePicker();
    };

    /**
     * Ini view, data and action bind
     */
    var initializationFunc = function(){
        iniGridInfo();
        iniButtonAction();
        otherActionBind();

        toolFunc.resetJqgrid();

        iniContorlData();
    };

    initializationFunc();
});

